package com.googlecode.npgame.screens;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;
import android.opengl.Matrix;
import android.view.MotionEvent;

import com.googlecode.npgame.assets.Assets;
import com.googlecode.npgame.graphics.shaders.Program;

/**
 * Represents a menu overlay.
 * 
 * @author Josh (joshbruning)
 */
public abstract class MenuScreen extends Screen {

  protected List<MenuOption> menuOptions;

  private FloatBuffer squareVB;
  private Program program;
  private float[] viewMatrix = new float[16];
  private float[] projMatrix = new float[16];

  public MenuScreen() {
    super();
    this.menuOptions = new ArrayList<MenuOption>();
  }

  public void onSurfaceCreated(GL10 unused, EGLConfig config) {
    // Set the background frame color to white.
    GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    initShapes();
    this.program = Assets.getSimpleProgram();
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    return true;
  }

  private void initShapes() {
    float squareCoords[] = { -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0.5f, 0.5f, 0,
        -0.5f, 0.5f, 0 };
    ByteBuffer vbb = ByteBuffer.allocateDirect(squareCoords.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    squareVB = vbb.asFloatBuffer();
    squareVB.put(squareCoords);
    squareVB.position(0);
  }

  public void onDrawFrame(GL10 unused) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
    this.program.use();
    GLES20.glVertexAttribPointer(this.program.getVertexHandle(), 3,
        GLES20.GL_FLOAT, false, 12, squareVB);
    GLES20.glEnableVertexAttribArray(this.program.getVertexHandle());
    this.program.setProjectionMatrix(projMatrix);
    this.program.setModelViewMatrix(viewMatrix);
    GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
  }

  public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);
    float ratio = (float) width / height;
    Matrix.frustumM(projMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
    Matrix.setLookAtM(viewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
  }
}
